package com.eascs.ticket.ticket.controller;

import javax.inject.Inject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.common.util.ObjectUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.ticket.common.entity.EntityUtil;
import com.eascs.ticket.common.entity.StatusConstant;
import com.eascs.ticket.ticket.entity.TicketWatcher;
import com.eascs.ticket.ticket.entity.TicketWatcherDelete;
import com.eascs.ticket.ticket.form.GetEditViewForm;
import com.eascs.ticket.ticket.form.TicketWatcherForm;
import com.eascs.ticket.ticket.service.TicketWatcherService;
import com.eascs.web.sso.NoPermissionException;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@RestController
public class TicketWatcherRestController extends BaseRestController {

	@Inject
	private TicketWatcherService ticketWatcherService;

	@RequestMapping(value = "/ticket/opt/getWatcherEditView")
	public HtmlRestResult getWatcherEditView(GetEditViewForm getEditViewForm) {
		TicketWatcher ticketWatcher = null;
		if (StringUtil.isEmpty(getEditViewForm.getId())) {
			ticketWatcher = new TicketWatcher();
			ticketWatcher.setTicketId(getEditViewForm.getTicketId());
		} else {
			ticketWatcher = ticketWatcherService.getTicketWatcherById(getEditViewForm.getId());
		}
		ViewContext.put("ticketWatcher", ticketWatcher);
		return HtmlRestResult.popHtmlFragment("/ticket/opt/getWatcherEditView");
	}

	@RequestMapping(value = "/ticket/opt/saveTicketWatcher")
	public BaseRestResult<String> saveTicketWatcher(TicketWatcherForm ticketWatcherForm) {
		TicketWatcher ticketWatcher = new TicketWatcher();
		ObjectUtil.copySimpleProperties(ticketWatcherForm, ticketWatcher);
		EntityUtil.initInsertEntity(ticketWatcher);
		ticketWatcher.setStatus(StatusConstant.STATUS_OK);
		this.ticketWatcherService.insertTicketWatcher(ticketWatcher);
		return BaseRestResult.refresh();
	}

	@RequestMapping(value = "/ticket/opt/deleteTicketWatcher")
	public BaseRestResult<String> deleteTicketWatcher(TicketWatcherForm ticketWatcherForm) {
		checkPermission(ticketWatcherForm.getId());
		TicketWatcherDelete ticketWatcherDelete = new TicketWatcherDelete();
		ticketWatcherDelete.setId(ticketWatcherForm.getId());
		EntityUtil.initUpdateEntity(ticketWatcherDelete);
		this.ticketWatcherService.deleteTicketWatcher(ticketWatcherDelete);
		return BaseRestResult.refresh();
	}

	public void checkPermission(String id) {
		User user = UserHolder.getUser();
		if (user.isSuperAdministrator())
			return;
		TicketWatcher ticketWatcher = this.ticketWatcherService.getTicketWatcherById(id);
		if (user.getCode().equals(ticketWatcher.getCreator()))
			return;
		throw new NoPermissionException("您无权删除！");
	}
}
